<template>
  <div class="indexpage">

      
      <div class="user-list">
        <!-- 搜索栏 -->
        <el-card class="search-card">
          <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="用户名">
              <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="resetSearch">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 用户表格 -->
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <el-button type="primary" @click="openAddDialog">
                <el-icon><Plus /></el-icon>
                添加用户
              </el-button>
              
              <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedIds.length">
                <el-icon><Delete /></el-icon>
                批量删除
              </el-button>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="tableData"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="username" label="用户名" width="150"/>
            <el-table-column prop="nickname" label="昵称" width="150"/>
            <el-table-column prop="role" label="身份" width="100">
              <template #default="{ row }">
                {{ row.role === 'admin' ? '管理员' : '用户' }}
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号" width="150"/>
            <el-table-column prop="email" label="邮箱" width="150"/>
            <el-table-column prop="address" label="地址" width="222"/>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button-group>
                  <el-button type="success" @click="openEditDialog(row)" size="small">
                    <el-icon><EditPen /></el-icon>
                    编辑
                  </el-button>
                  <el-button type="danger" @click="handleDelete(row)" size="small">
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 15, 20]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>

    <!-- 添加用户对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加用户" width="500px">
      <el-form 
        ref="addFormRef" 
        :model="addForm" 
        :rules="rules" 
        label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="addForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="addForm.nickname" placeholder="请输入昵称" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="身份" prop="role">
          <el-select v-model="addForm.role" placeholder="请选择身份">
            <el-option label="管理员" value="admin" />
            <el-option label="用户" value="user" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdd" :loading="addLoading">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑用户" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="editForm.nickname" autocomplete="off" />
        </el-form-item>
        <el-form-item label="身份" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择身份">
            <el-option label="管理员" value="admin" />
            <el-option label="用户" value="user" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" autocomplete="off" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// import { Search, Refresh, Plus, Delete, EditPen } from '@element-plus/icons-vue'

import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const loading = ref(false)
const addLoading = ref(false)
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedIds = ref([])

// 添加用户相关
const addDialogVisible = ref(false)
const addFormRef = ref()
const addForm = reactive({
  username: '',
  password: '',
  nickname: '',
  phone: '',
  email: '',
  role: 'user'
})

// 编辑用户相关
const editDialogVisible = ref(false)
const editFormRef = ref()
const editForm = reactive({
  id: '',
  username: '',
  nickname: '',
  role: 'user',
  phone: '',
  email: '',
  address: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择身份', trigger: 'change' }
  ]
}

// 编辑表单验证规则
const editRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择身份', trigger: 'change' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const searchForm = reactive({
  username: '',
})

// 获取用户列表
const getUserList = async () => {
  loading.value = true
  try {
    const res = await request({
      url: '/user/page',
      method: 'get',
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        ...searchForm
      }
    })
    tableData.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 打开添加用户对话框
const openAddDialog = () => {
  addDialogVisible.value = true
}

// 提交添加用户
const submitAdd = async () => {
  try {
    await addFormRef.value.validate()
    addLoading.value = true
    
    await request({
      url: '/user',
      method: 'post',
      data: addForm
    })
    
    ElMessage.success('添加成功')
    addDialogVisible.value = false
    resetAddForm()
    getUserList()
  } catch (error) {
    console.error('添加用户失败:', error)
    if (error !== 'validate') {
      ElMessage.error('添加失败')
    }
  } finally {
    addLoading.value = false
  }
}

// 重置添加表单
const resetAddForm = () => {
  addFormRef.value?.resetFields()
  Object.assign(addForm, {
    username: '',
    password: '',
    nickname: '',
    phone: '',
    email: '',
    role: 'user'
  })
}

// 打开编辑对话框并填充数据
const openEditDialog = (row) => {
  Object.assign(editForm, {
    id: row.id,
    username: row.username,
    nickname: row.nickname,
    role: row.role || 'user',
    phone: row.phone,
    email: row.email,
    address: row.address
  })
  editDialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  try {
    await editFormRef.value.validate()
    await request({
      url: '/user',
      method: 'post',
      data: editForm
    })
    ElMessage.success('修改成功')
    editDialogVisible.value = false
    getUserList()
  } catch (error) {
    console.error('修改用户失败:', error)
    if (error !== 'validate') {
      ElMessage.error('修改失败')
    }
  }
}

// 处理表格选中项变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedIds.value.length} 条记录吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request({
        url: '/user/del/batch',
        method: 'post',
        data: { ids: selectedIds.value }
      })
      ElMessage.success('删除成功')
      selectedIds.value = []
      getUserList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 删除单个用户
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该用户吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request({
        url: `/user/${row.id}`,
        method: 'delete'
      })
      ElMessage.success('删除成功')
      getUserList()
    } catch (error) {
      console.error('删除用户失败:', error)
    }
  }).catch(() => {})
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getUserList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getUserList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getUserList()
}

onMounted(() => {
  getUserList()
})
</script>

<style scoped>
.indexpage {
  width: 100%;
  height: 99vh;
  overflow: hidden;
}
.indexpage main {
  width: 100%;
  height: 80vh;
  display: flex;
}
.user-list {
  flex: 1;
  padding: 20px;
  overflow: auto;
}
.search-card {
  margin-bottom: 20px;
}
.table-card {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>